//
//  LZMyRecordVideoTableView.m
//  laziz_Consumer
//
//  Created by xbn_iMac on 2016/12/8.
//  Copyright © 2016年 XBN. All rights reserved.
//

#import "LZMyRecordVideoTableView.h"
#import "LZVideoTableViewCell.h"
#import "LZCustomPlayerView.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "UITableView+LZTableView.h"
#import "LZMyFavoriteModel.h"
#import "LZVideoListModel.h"
#import "Masonry.h"
#import "LZPlayVideoManager.h"
#import "LZZanAndCollectStatusPresenter.h"
#import "LZNoDataPublicView.h"

@interface LZMyRecordVideoTableView ()<UITableViewDelegate,UITableViewDataSource,LZ_MainTableViewCellDelegate,LZPlayVideoManagerDelegate>

@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) LZCustomPlayerView *playerView;
@property (nonatomic, strong) NSIndexPath *currentPlayCellIndexPath;

@property (nonatomic, assign) NSInteger removeCnt;      // 记录移除的个数(**** 用于待评价类型 ****)

@property (nonatomic, assign) int page;
@property (nonatomic, assign) int limit;

@end

@implementation LZMyRecordVideoTableView
-(instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style {
    self = [super initWithFrame:frame style:style];
    if (self) {
        self.separatorColor = [UIColor clearColor];
        self.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.backgroundColor = UIColorFromRGB(0xeeeeee, 1);
        [LZPlayVideoManager shareManager].playVideoManagerDelegate = self;
        [self registerCell];
        [self configBaseData];
        self.delegate = self;
        self.dataSource = self;
    }
    return self;
}

#pragma mark - Public Method

- (void)stopPlayVideo {
    
    [[LZPlayVideoManager shareManager] stopPlayWithPlayerView:self.playerView];
}

- (void)startPlayVideo {
    WS(weakSelf);
   self.currentPlayCellIndexPath = [[LZPlayVideoManager shareManager] goOnPlayWithCellIndexPath:self.currentPlayCellIndexPath playerView:self.playerView tableView:self playCountAddBlock:^(NSInteger totleCount) {
       [weakSelf addViewsCountWithIndexPath:weakSelf.currentPlayCellIndexPath withCount:totleCount];
   }];
}

- (void)checkHaveData {
    if (self.dataArr.count == 0) {
        if (self.subTableViewDelegate && [self.subTableViewDelegate respondsToSelector:@selector(requestDateWithTag:andPrameter:andPage:andLimit:resultSuccess:)]) {
            if (self.mj_footer.state != MJRefreshStateRefreshing) {
                [self.mj_footer beginRefreshing];
            }
        }
    }
    else {
        if (self.type == MyRecordsType_Favorites) {
            // 为了保持数据的统一性，做一下视频是否收藏的校验
            BOOL isRefresh = NO;
            for (LZCollectStatusModel *statusModel in [LZZanAndCollectStatusPresenter shareInstance].collectVideoArray) {
                NSArray *result = [self.dataArr filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self.videoDTO.videoId = %@",statusModel.collectId]];
                if (result.count>0) {
                    LZMyFavoriteModel *favoriteModel = result[0];
                    LZVideoListModel *model = favoriteModel.videoDTO;
                    if (model.isStore != statusModel.isStore) {
                        isRefresh = YES;
                        model.isStore = statusModel.isStore;
                    }
                }
            }
            if (isRefresh) {
                [self reloadData];
            }
        }
        
    }
}

#pragma mark - configure Super Refresh method


- (void)upLoadMoreData {
    [self requestList];
}

- (void)requestList {
    
    WS(weakSelf)
    
    NSInteger removeCount = 0;
    
    if (self.type == MyRecordsType_Favorites) {
        if (self.dataArr.count>0) {
            NSArray *result = [self.dataArr filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self.videoDTO.isStore = NO"]];
            removeCount = result.count;
        }
    }
    else if (self.type == MyRecordsType_ToBeReviewed) {
        removeCount = self.removeCnt;
    }
    
    NSDictionary *prameter = @{@"removeCnt":[NSString stringWithFormat:@"%ld",removeCount]};
    
    [self.subTableViewDelegate requestDateWithTag:1 andPrameter:prameter andPage:self.page andLimit:self.limit resultSuccess:^(NSArray *result,NSString *timestamp) {

        [weakSelf.mj_footer endRefreshing];
        
        if (result) {
            weakSelf.page ++;
            
            if (result.count>0) {
                [weakSelf.dataArr addObjectsFromArray:result];
                [weakSelf fd_reloadDataWithoutInvalidateIndexPathHeightCache];
                
                //默认播放第一个视频
                self.currentPlayCellIndexPath = [[LZPlayVideoManager shareManager] playVideoWhenTableViewStopScrollWithTableView:self cellIndexPath:self.currentPlayCellIndexPath playerView:self.playerView playCountAddBlock:^(NSInteger totleCount) {
                    
                    [weakSelf addViewsCountWithIndexPath:weakSelf.currentPlayCellIndexPath withCount:totleCount];
                }];
            }
            else {
                
                if (weakSelf.dataArr.count == 0) {
                    [LZNoDataPublicView showNoDataViewInView:weakSelf];
                    [weakSelf setNullStringFooterText];
                }
                else {
                    [LZNoDataPublicView hiddenNoDataViewInView:weakSelf];
                    [weakSelf setNoMoreDataFooterText];
                }
                
                [weakSelf.mj_footer endRefreshingWithNoMoreData];
            }
        }
    }];
}

#pragma mark - Private Method

/**
 添加浏览次数
 
 @param indexP <#indexP description#>
 @param totleCount <#totleCount description#>
 */
- (void)addViewsCountWithIndexPath:(NSIndexPath *)indexP withCount:(NSInteger)totleCount
{
    LZVideoListModel *m = [self getVideoListModelWithIndex:indexP.row];;
    m.playCount = totleCount;
    LZVideoTableViewCell *cell = [self cellForRowAtIndexPath:indexP];
    [cell getViewsCountLabel].text = [NSString stringWithFormat:@"%ld",(long)totleCount];
}

- (void)registerCell
{
    [self registerClass:[LZVideoTableViewCell class] forCellReuseIdentifier:@"videocell"];
}

- (void)configBaseData {
    self.page = 1;
    self.limit = 10;
    self.dataArr = [NSMutableArray array];
}

- (LZVideoListModel*)getVideoListModelWithIndex:(NSInteger)index {
    LZVideoListModel *model = nil;
    if (self.type == MyRecordsType_ToBeReviewed) {
        model = self.dataArr[index];
    }
    else if (self.type == MyRecordsType_Favorites) {
        LZMyFavoriteModel *favoriteModel = self.dataArr[index];
        model = favoriteModel.videoDTO;
    }
    else if (self.type == MyRecordsType_History)
    {
        
    }
    return model;
}

#pragma mark -
#pragma mark tableview delegate datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [tableView fd_heightForCellWithIdentifier:@"videocell" configuration:^(id cell) {
        LZVideoTableViewCell *cellTemp = (LZVideoTableViewCell *)cell;
        [cellTemp loadDataWithIndex:indexPath WithShowHeadView:YES showCellBtns:NO showCouponAndGroupsView:NO];
        cellTemp.model = [self getVideoListModelWithIndex:indexPath.row];
    }];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LZVideoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"videocell"];
    if (cell == nil) {
        cell = [[LZVideoTableViewCell  alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"videocell"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.mainDelegate = self;
    cell.cellClickDelegate = self.videoDelegate;
    cell.vcType = self.type;
    
    [cell loadDataWithIndex:indexPath WithShowHeadView:YES showCellBtns:NO showCouponAndGroupsView:NO];
    
    cell.model = [self getVideoListModelWithIndex:indexPath.row];
    
    WS(weakSelf)
    cell.removeCellBlock = ^(NSIndexPath *indexPath,LZVideoListModel *model) {
        [weakSelf.dataArr removeObject:model];
        [weakSelf deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        weakSelf.removeCnt ++;
        if (weakSelf.dataArr.count == 0) {
            [weakSelf.mj_footer beginRefreshing];
        }
    };
    
    return cell;
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if(!decelerate){//缓慢拖动.手指离开时
        WS(wSelf);
        self.currentPlayCellIndexPath = [[LZPlayVideoManager shareManager] playVideoWhenTableViewStopScrollWithTableView:self cellIndexPath:self.currentPlayCellIndexPath playerView:self.playerView playCountAddBlock:^(NSInteger totleCount) {
           [wSelf addViewsCountWithIndexPath:wSelf.currentPlayCellIndexPath withCount:totleCount];
        }];
    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    WS(wSelf);
    self.currentPlayCellIndexPath = [[LZPlayVideoManager shareManager] playVideoWhenTableViewStopScrollWithTableView:self cellIndexPath:self.currentPlayCellIndexPath playerView:self.playerView playCountAddBlock:^(NSInteger totleCount) {
       [wSelf addViewsCountWithIndexPath:wSelf.currentPlayCellIndexPath withCount:totleCount];
    }];
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //滑动时判断当前播放的cell是否已经离开屏幕.已经离开,停止播放
    [[LZPlayVideoManager shareManager] removePlayViewWhenTableViewDidScrollWithTableView:self cellIndexPath:self.currentPlayCellIndexPath];
}

/**
 点击视频海报播放协议
 */
- (void)playVideoWhenClickVideoCoverImgWithIndex:(NSIndexPath *)cellIndexPath
{
    [self scrollToRowAtIndexPath:cellIndexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
    WS(wSelf);
    self.currentPlayCellIndexPath = [[LZPlayVideoManager shareManager] playVideoWhenClickVideoCoverImgWithIndexPath:cellIndexPath playerView:self.playerView playCountAddBlock:^(NSInteger totleCount) {
        [wSelf addViewsCountWithIndexPath:wSelf.currentPlayCellIndexPath withCount:totleCount];
    }];
    
}

#pragma mark -
#pragma mark  播放控制器获取资源delegate
- (NSString *)playVideoManagerGetVideoUrlWith:(NSIndexPath *)cellIndexPath
{
    LZVideoListModel *model = [self getVideoListModelWithIndex:cellIndexPath.row];
    return model.videoUrl;
}

- (UIView *)playVidewManagerGetPlayBackgroundViewWith:(NSIndexPath *)cellIndexPath
{
    LZVideoTableViewCell *cell = [self cellForRowAtIndexPath:cellIndexPath];
    return cell.playerBgView;
}

- (NSString *)playVideoManagerGetVideoIdWithIndexPath:(NSIndexPath *)cellIndexPath
{    
    LZVideoListModel *model = [self getVideoListModelWithIndex:cellIndexPath.row];
    return model.videoId;
}

#pragma mark -
#pragma mark 控件初始化
- (LZCustomPlayerView *)playerView
{
    if (!_playerView) {
        _playerView = [[LZCustomPlayerView alloc] init];
        _playerView.playCircle = YES;
    }
    
    return _playerView;
}

@end
